package com.sun.async.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.async.entity.ImportTask;
import com.sun.async.enums.ImportTaskStatusEnum;
import com.sun.async.mapper.ImportTaskMapper;
import com.sun.async.service.FileStorageService;
import com.sun.async.service.ImportTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * 导入任务服务实现类
 */
@Service
public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportTask> implements ImportTaskService {

    @Autowired
    private FileStorageService fileStorageService;

    @Override
    public Long createImportTask(File file, String taskName) {
        ImportTask task = new ImportTask();
        task.setTaskName(taskName);
        task.setOriginalFileName(file.getName());
        task.setStatus(ImportTaskStatusEnum.WAITING.getCode());
        task.setCreateTime(new Date());

        this.save(task);
        return task.getId();
    }

    @Override
    public ImportTask getTaskDetail(Long taskId) {
        return this.getById(taskId);
    }

    @Override
    public List<ImportTask> listAllTasks() {
        return this.list();
    }

    @Override
    public void downloadErrorFile(Long taskId, HttpServletResponse response) throws IOException {
        ImportTask task = this.getById(taskId);
        if (task == null || task.getErrorFilePath() == null) {
            throw new IllegalArgumentException("任务不存在或错误文件不存在");
        }

        String fileName = task.getOriginalFileName();
        fileName = fileName.substring(0, fileName.lastIndexOf(".")) + "_error.xlsx";

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

        // 输出文件
        try (OutputStream os = response.getOutputStream()) {
            fileStorageService.downloadFile(task.getErrorFilePath(), os);
        }
    }
}